const fs = require('fs')
const path = require('path')

fs.rmSync(path.resolve(__dirname, '../node_modules/.vite'), { recursive: true, force: true })

const serverlessFinchConfigurePath = path.resolve(__dirname, '../node_modules/serverless-finch/lib/configure.js')
const awsRegionUrlsPath = path.resolve(__dirname, '../node_modules/serverless-finch/lib/resources/awsRegionUrls.json')
const CORSPolicy = path.resolve(__dirname, '../node_modules/serverless-finch/lib/resources/CORSPolicy.json')

fs.writeFileSync(
  serverlessFinchConfigurePath,
  fs.readFileSync(serverlessFinchConfigurePath, 'utf8').replace(/arn:aws:s3/m, 'arn:aws-cn:s3')
)

fs.writeFileSync(CORSPolicy, fs.readFileSync(CORSPolicy, 'utf8').replace(/amazonaws.com/m, 'amazonaws.com.cn'))

fs.writeFileSync(
  awsRegionUrlsPath,
  fs
    .readFileSync(awsRegionUrlsPath, 'utf8')
    .replace(
      /"sa-east-1": "s3-website-sa-east-1.amazonaws.com"\n}/m,
      '"sa-east-1": "s3-website-sa-east-1.amazonaws.com",\n  "cn-north-1": "s3-website.cn-north-1.amazonaws.com.cn",\n  "cn-northwest-1": "s3-website.cn-northwest-1.amazonaws.com.cn"\n}'
    )
)
